<?php
namespace app\money\controller;
use app\admin\common\Base;
use think\Db;
use think\Session;
use app\admin\common\Excel;
//资金转账
class Fundtf extends Base
{

    public function add()
    {   
        if (request()->isPost()) {
            $data = $this->request->param();
            $grid =$data['grid'];//获取到数组
            $date=strtotime($data['date']);//时间戳转换
            $sess=Session::get('user_info');//获取登录用户的值
            $sum=0;
            $ed=[];
            foreach ($grid as $k => $v) {//合计计算
                $sum+=$v['money'];  
            }
                if (!isset($data['oid'])) {//判断有没有审核值过来有时候输出的内容 审核输出的内容
                    $da=[//要存入数据库的内容
                        'time'=>$date,//时间
                        'bill'=>$data['number'],//备注
                        'preparer'=>$sess['username'],//制单人
                        'revieweras'=>1,//审核状态 0时开启1是关闭
                        'is_del'=>$sess['is_del'],//表状态 0存在 1删除
                        'enterprise_id'=>$sess['enterprise_id'],//企业ID
                        'user_id'=>$sess['id'],//制单人ID          
                    ];
                }else{//保存新增输出的内容
                    $da=[
                        'time'=>$date,//时间
                        'bill'=>$data['number'],//备注
                        'preparer'=>$sess['username'],//制单人
                        'reviewer'=>$sess['username'],//审核人
                        'revieweras'=>0,//审核状态 0是审核 1是未审核
                        'reviewerid'=>$sess['id'],//审核人ID
                        'is_del'=>$sess['is_del'],//表状态 0存在 1删除
                        'enterprise_id'=>$sess['enterprise_id'],//企业ID
                        'user_id'=>$sess['id'],//制单人ID
                        'editid'=>$sess['id'],//编辑人ID
                        'editname'=>$sess['username']//编辑人名字          
                    ];
                }   
                    if (isset($data['edit'])) {//编辑的内容
                        $fun=Db('mony_fundtf')->where('id' , $data['id'])->update(['editid' => $sess['id'],'editname' => $sess['username']]);//更新编辑人
                    }else{
                        //判断是不是点击审核
                        if (isset($data['sh'])) {
                            //更新主表某个字段
                            $fun=Db('mony_fundtf')->where('id' , $data['id'])->update(['reviewer' => $sess['username'] , 'reviewerid' => $sess['id'] , 'revieweras' => 0]);
                            if ($fun) {//审核成功返回的内容
                                return json(['cone' => 1]);
                            }else{
                                return json(['cone' => 2 ]);
                            }
                        }
                        $fun=Db('mony_fundtf')->insertGetId($da);//输出数据库返回主键ID
                    }
                        if (isset($fun)) {//判断是否存在主键ID输出的内容
                            foreach($grid as $k=>$v){//摧毁数据为空的数组
                                for ($i=0; $i <sizeof($grid) ; $i++) { 
                                    if ($grid[$i]=='') {
                                    unset($grid[$i]);//摧毁数组
                                }
                            }
                                switch ($v['account_name']) //前段获取到的值转换
                                {
                                    case "现金":$nameinid='1';
                                    break;
                                    case "银行存款":$nameid='2';
                                    break;
                                    case "微信转账":$nameid='3';
                                    break;
                                    case "0308":$nameid='4';
                                    break;
                                };
                                switch ($v['account_name_in'])
                                {
                                    case "现金":$nameinid='1';
                                    break;
                                    case "银行存款":$nameinid='2';
                                    break;
                                    case "微信转账":$nameinid='3';
                                    break;
                                    case "0308":$nameinid='4';
                                    break;
                                };   
                                    if (isset($data['edit'])) {//修改子表合并数据输出的内容
                                        $dat = [//要存入数据库的内容
                                        'time' => $date,
                                        'account_name' => $v['account_name'],
                                        'account_name_in' => $v['account_name_in'],
                                        'account_nameid' => $nameid,
                                        'account_name_inid' => $nameinid,
                                        'money' => $v['money'],
                                        'total' => $sum,
                                        'bill' => $data['number'],
                                        'settlement_no' => $v['settlement_no'],
                                        'remarks' => $v['remarks'],
                                        'settle_type_name' => $v['settle_type_name'],
                                        'enterprise_id' => $sess['enterprise_id'],
                                        'is_del' => $sess['is_del']
                                    ];
                                    array_push($ed,$dat);
                                }else{
                                        $dat = [//要存入数据库的内容
                                        'time' => $date, 
                                        'fundtf' => $fun,
                                        'account_name' => $v['account_name'],
                                        'account_name_in' => $v['account_name_in'],
                                        'account_nameid' => $nameid,
                                        'account_name_inid' => $nameinid,
                                        'money' => $v['money'],
                                        'total' => $sum,
                                        'bill' => $data['number'],
                                        'settlement_no' => $v['already_jine'],
                                        'remarks' => $v['not_jine'],
                                        'settle_type_name' => $v['settle_type_name'],
                                        'enterprise_id' => $sess['enterprise_id'],
                                        'is_del' => $sess['is_del']
                                    ];
                                        $funs = db('mony_fundtfs')->insert($dat);//循环新增添加到数据库      
                                    }        
                                }   
                            if (!empty($ed)) {//判断是不是在编辑页面点击输出的内容
                                $i = 0;
                                $pd = 0;
                                $funid = db('mony_fundtfs')->where('fundtf',$data['id'])->where('is_del',0)->select();//查询子表的数据
                                foreach($funid as $kk=>$vv){//遍历子表数组 给数组追加数据
                                    $ed[$i]['id']=$vv['id'];
                                    $i++;                                
                                }
                                for ($a=0; $a <sizeof($ed) ; $a++) {//组合后的数组循环更新值输出的内容
                                    $id = $ed[$a];
                                    if (!isset($id['id'])) {//判断是不是在编辑页面添加数据输出的内容
                                        $ed[$a]['fundtf'] = $data['id'];//向数组追加 关联主表的ID
                                        Db('mony_fundtfs')->where('fundtf',$data['id'])->field('id',true)->insert($ed[$a]);//逐条添加新子表数据
                                    }else{//更新子表输出的内容
                                        $funs=Db('mony_fundtfs')->where('id',$id['id'])->field('id',true)->update($ed[$a]);
                                        $pd+=$funs;//判断是否更新成功输出的内容
                                    }    
                                }
                                if ($pd!==0) {//存入数据库成功输出的内容
                                    return json(['cone'=>1,'edit'=>1]);
                                }else{
                                    return json(['cone'=>2,'edit'=>2]);
                                }
                            }   
                                if ($funs) {//存入数据库成功输出的内容
                                    return json(['cone'=>1]);
                                }else{
                                    return json(['cone'=>2]);
                                }   
                            }else{
                                return json(['cone'=>2,]);
                            }    
                        }
                        $account = db('account')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->select();
                        $sn = db('mony_fundtfs')->where('is_del',0)->order('id desc')->find();
                        $snn = $sn['bill'];
                        $str = str_split($snn,1);
                        $zs = '';
                        $in = '';
                        for ($i=0; $i <count($str) ; $i++) {
                            if (is_numeric($str[$i])) {
                                $in .=$str[$i];
                            }else{
                                $zs .=$str[$i];
                            }
                        }
                        $sns = $in+1;
                        $snsn = $zs.$sns;
                        $this->assign('sn',$snsn);
                        $this->assign('acc',$account);
                        return $this->fetch();
                    }
                    public function edit()
                    {   
                        $data = $this->request->param();
                        if (isset($data['ajax']) && $data['ajax']==100) {
                $map='';                                    //给$map赋值为空
                $page=isset($data['page'])?$data['page']:1; //是否有第几页有就返回本身不然就返回1赋值给$page
                $page=intval($page);                        //获取变量的整数值
                $limit=isset($data['rows'])?$data['rows']:10;//是否有多少条数有就返回本身不然就返回10赋值给$limit
                $limit=intval($limit);              //获取变量的整数值
                $start=$limit*($page-1);//0
                $list = db('mony_fundtfs')->where('fundtf',$data['id'])->where('enterprise_id',$this->EnterpriseId)->select();
                $count = db('mony_fundtfs')->where('fundtf',$data['id'])->where('enterprise_id',$this->EnterpriseId)->count();
                //少于5条则填充
                if (5 - $count > 0) {
                    for ($i = 0; $i < 5 - $count; $i++) {
                        array_push($list, []);
                    }
                }
                return $this->grid_data($list,$count,$page,$limit);//返回查询到的结果，查询到结果的种条数，页数，条数给grid
            }
            $list = db('mony_fundtf')->where('id',$data['order_id'])->where('enterprise_id',$this->EnterpriseId)->find();
            //判断是否已审核输出的内容
            if (!empty($list['reviewer'])) {
                $sh=1;
            }else{
                $sh=0;
            }
            $this->assign('sh',$sh);        
            $this->assign('id', $data['order_id']);
            return $this->fetch();
    }
    //删除方法
    public function del(){
        $data = $this->request->param();
        if (!isset($data['del'])) {//判断是否是多选删除输出的内容
            $list=db('mony_fundtf')->where('id',$data['id'])->setField('is_del','1');//修改主表删除字段为1
            if ($list) {
                    db('mony_fundtfs')->where('fundtf',$data['id'])->setField('is_del','1');//修改子表删除字段为1
                    return json(['code'=>1]);
                }else{
                    return json(['code'=>2]);
                }   
        }else{//多选时输出的内容
            $id=$data['ids'];
            foreach($id as $k=>$v){
                $dell=db('mony_fundtf')->where('id',$v)->setField('is_del','1');//修改主表删除字段为1
                if ($dell) {
                    $de=db('mony_fundtfs')->where('fundtf',$v)->setField('is_del','1');//修改子表删除字段为1
                }
            }
            if($de){
                return json(['code'=>1]);
            }else{
                return json(['code'=>2]);
            }
            
        }
    }
    public function index()
    {
        $data = $this->request->param();
        $acc = db('account')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->select();
        $this->assign('acc',$acc);
        $this->assign('o_type',15);//高级搜索状态（15：资金转账记录）

        if (isset($data['ajax']) && $data['ajax']==100) {
            $map='';                                    //给$map赋值为空
            $page=isset($data['page'])?$data['page']:1; //是否有第几页有就返回本身不然就返回1赋值给$page
            $page=intval($page);                        //获取变量的整数值
            $limit=isset($data['rows'])?$data['rows']:10;//是否有多少条数有就返回本身不然就返回10赋值给$limit
            $limit=intval($limit);              //获取变量的整数值
            $start=$limit*($page-1);//0
            //搜索功能
            if (isset($data['search'])) {
                $time1=strtotime($data['startdate']);//将获取过来的时间转换为时间戳
                $time2=strtotime("+1 day",strtotime($data['enddate']));//将获取过来的时间转换为时间戳切获取到的时间加一天
                //搜索
                $listt=[];
                $sqlch=[];
                $lists=db('mony_fundtf')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId);
                $sql=db('mony_fundtfs')->where('is_del',0);
                $sql = $data['matchcon'] == '' ? $sql : $sql->where('bill', 'like', '%'. $data['matchcon'] .'%')->whereOr('remarks', 'like', '%'. $data['matchcon'] . '%');
                $sql=$time1=='' ? $sql : $sql->whereTime('time', 'between', [$time1, $time2]);
                $sql=$data['acct'] =='' || $data['acct'] == 0 ? $sql : $sql->where('account_name',$data['acct']);
                $sql=$data['acctRecId'] =='' || $data['acctRecId'] == 0 ? $sql : $sql->where('account_name_in',$data['acctRecId']);
                $sql=$sql->select();
                foreach($sql as $k=>$v){
                    array_push($sqlch,$v['fundtf']);
                }
                $cd=array_unique($sqlch);
                $lists=$lists->where('id','in',$cd);
                $lists=$lists->select();
                foreach($lists as $key=>$value){
                    $lists[$key]['son']=db('mony_fundtfs')->where('fundtf',$value['id'])->select();//主表追加子表数据
                    $value['preparer'] = db('auth_user')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->where('id',$value['user_id'])->value('name');
                    $value['reviewer'] = db('auth_user')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->where('id',$value['user_id'])->value('name');
                    array_push($listt,$lists[$key]);
                    // $list[$key]['time']=date('Y-m-d',$value['time']);//主表时间转换日期格式
                }
                $listx=array_reverse($listt);//数组倒序排序
                $list=array_slice($listx,$start,$limit); //数组分页输出
                $count=sizeof($list);
            }else{
                //高级搜索
                if (isset($data['searchs'])) {
                    $page=isset($data['page'])?$data['page']:1; //是否有第几页有就返回本身不然就返回1赋值给$page
                    $page=intval($page);                        //获取变量的整数值
                    $limit=isset($data['rows'])?$data['rows']:10;//是否有多少条数有就返回本身不然就返回10赋值给$limit
                    $limit=intval($limit);              //获取变量的整数值
                    $start=$limit*($page-1);//0
                    $time1 = strtotime($data['fromDate']);
                    $time2 = strtotime($data['toDate']);
                    $sql = db('mony_fundtf')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->limit($start,$limit);
                    //制单人
                    $sql = $data['usersCreatId'] == '' ? $sql : $sql->where('user_id',$data['usersCreatId']);
                    //最后修改人usersModifyId
                    $sql = $data['usersModifyId'] == '' ? $sql : $sql->where('editid',$data['usersModifyId']);
                    //审核人
                    $sql = $data['usersChecksId'] == '' ? $sql : $sql->where('reviewerid',$data['usersChecksId']);
                    //审核状态
                    $sql = $data['checkStatusId'] == '' ? $sql : $sql->where('revieweras',$data['checkStatusId']);
                    if (!empty($data['remarkCon']) || !empty($data['payAccId']) || !empty($data['recAccId']) || !empty($time1)) {
                        $str = db('mony_fundtfs')->where('is_del',0);
                        //备注
                        $str = $data['remarkCon'] == '' ? $str : $str->where('remarks | bill','like','%'.$data['remarkCon'].'%');
                        //付款账户
                        $str = $data['payAccId'] == '' ? $str : $str->where('account_nameid',$data['payAccId']);
                        //收款账户
                        $str = $data['recAccId'] == '' ? $str : $str->where('account_name_inid',$data['recAccId']);
                        //日期
                        $str = $data['fromDate'] == '' && $data['toDate'] == '' ? $str : $str->whereTime('time', 'between', [$time1, $time2]);
                        $fun = $str->column('fundtf');
                        $arr = array_unique($fun);
                        sort($arr);
                    }
                    $sql = !isset($arr) ? $sql : $sql->where('id','in',$arr);
                    $list=$sql->order('id desc')->select();
                    foreach($list as $k=>$v){
                        $list[$k]['son'] = db('mony_fundtfs')->where('is_del',0)->where('fundtf',$v['id'])->select();
                        $v['preparer'] = db('auth_user')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->where('id',$v['user_id'])->value('name');
                    $v['reviewer'] = db('auth_user')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->where('id',$v['user_id'])->value('name');
                    }
                    $count = count($list);
                }else{
                    $list =db('mony_fundtf')->where('enterprise_id',$this->EnterpriseId)->where('is_del',0)->limit($start,$limit)->order('id desc')->select();
                    $count =db('mony_fundtf')->where('enterprise_id',$this->EnterpriseId)->where('is_del',0)->count();
                    foreach ($list as $key => $value) {
                        $list[$key]['time']=date('Y-m-d',$value['time']);
                        $list[$key]['son'] = db('mony_fundtfs')->where('fundtf',$value['id'])->select();
                        $value['preparer'] = db('auth_user')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->where('id',$value['user_id'])->value('name');
                    $value['reviewer'] = db('auth_user')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->where('id',$value['user_id'])->value('name');
                    } 
                }
            }
            return $this->grid_data($list,$count,$page,$limit);//返回查询到的结果，查询到结果的种条数，页数，条数给grid
        }
        return $this->fetch();
    }
    //审核 反审核
    public function shenhe(){
        $data = $this->request->param();
        $arrid = explode(",", $data['id']);
        $sess=Session::get('user_info');
        $msg=null;
        if ($data['type']==1) {
            for ($i=0; $i <sizeof($arrid) ; $i++) {
                $list=db('mony_fundtf')->where('enterprise_id',$this->EnterpriseId)->where('id',$arrid[$i])->order('id desc')->select();
                $msg=$list[0]['bill'];
                if ($list[0]['reviewer']=='') {
                    $sh=db('mony_fundtf')->where('enterprise_id',$this->EnterpriseId)->where('id',$arrid[$i])->update(['reviewer'=>$sess['username'],'reviewerid'=>$sess['id'],'revieweras'=>0,]);
                } 
            }
            if ($sh) {
                return json(['code'=>1,'msg'=>$msg]);
            }else{
                return json(['code'=>2,'msg'=>'账单以审核']);    
            }    
        }else{
           for ($i=0; $i <sizeof($arrid) ; $i++) {
            $list=db('mony_fundtf')->where('enterprise_id',$this->EnterpriseId)->where('id',$arrid[$i])->order('id desc')->select();
            if ($list[0]['reviewer']!='') {
                $sh=db('mony_fundtf')->where('enterprise_id',$this->EnterpriseId)->where('id',$arrid[$i])->update(['reviewer'=>'','reviewerid'=>$sess['id'],'revieweras'=>1]);
            } 
        }
        if ($sh) {
            return json(['code'=>1,'msg'=>$list[0]['bill']]);
        }else{
            return json(['code'=>2,'msg'=>'账单以反审核']);    
        } 
    }

    }
    //导出
    public function export()
    {
        $data = $this->request->param();

        $rowid = explode(" ",$data['rowid']);
            // halt($rowid);
        $title = [
            'time' => '单据日期',
            'bill' => '单据编号',
            'remarks' => '单据备注',
            'account_name' => '转出账户',
            'account_name_in' => '转入账户',
            'money' => '金额',
            'settle_type_name' => '结束方式',
            'settlement_no' => '结算号'
        ]; 

        $arr_list = [];
            //查子条数
        $list = db('mony_fundtfs')->where('enterprise_id',$this->EnterpriseId)->where('fundtf','in',$rowid)->where('is_del',0)->order('id desc')->select();

        foreach ($list as $key => $value) {

            $list[$key]['time'] = date('Y-m-d',$value['time']);
            array_push($arr_list,$list[$key]);

        }

            $arr = db('mony_fundtfs')->where('enterprise_id',$this->EnterpriseId)->where('fundtf','in',$rowid)->where('is_del',0)->group('bill')->order('id desc')->select();//查出有几组 编号

            foreach ($arr as $k => $v) {

                $hj = db('mony_fundtfs')->where('enterprise_id',$this->EnterpriseId)->where('fundtf','in',$rowid)->where('is_del',0)->where('bill',$v['bill'])->sum('money');//计算合计

                $arr_hb = [
                    'id'=>$v['id']-1,
                    'time' => '',
                    'bill' => $v['bill'],
                    'remarks' => '',
                    'account_name' => '合计',
                    'account_name_in' => '',
                    'money' => $hj,
                    'settle_type_name' => '',
                    'settlement_no' => ''
                ]; 

                array_push($arr_list,$arr_hb);
            }

            foreach ($arr_list as $li => $row) {

                $distance[$li] = $row['id'];

            }
            // halt($arr_list);
            array_multisort($distance, SORT_DESC, $arr_list);//按照ID大小排序
            //添加标题到数组头部
            array_unshift($arr_list,$title);
            $kong_arr=$title;
            foreach ($kong_arr as $ke1 => $va1) {
                $kong_arr[$ke1]='';
            }
            for ($i=0; $i <3 ; $i++) { 
                array_unshift($arr_list,$kong_arr);
            }
             //根据此参数获取数据中的值，要与表格标题键名对应
            $keys=[];
            foreach ($title as $k2 => $v2) {
                array_push($keys, $k2);
            }
            $merge=[];
            $options=[];
            $o_type=-1;
            $merge=[//合并
            'start'=>5,
            'arr_zimu'=>['A','B','C'],
            'keyword'=>'bill',
        ];
        $options=[
                'alignCenter'=>['A','B','C','D','E','F','G','H'],//居中
                'bold'=>['A1:I3','A4:I4'],//加粗
                'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
            ];
            $title=[//标题
            'title'=>"资金转账单记录",
            'max_zimu'=>"H",
            'number'=>'3',
        ];
            $excel_export_title="资金转账单记录_" . date('Y-m-d_His') . '.xlsx';//文件名称
            $excel = new Excel();
            $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
            
            exit();
    }


}